const { app, httpServer } = require('./app.js');
const express = require('express');
const socket = require('./controller/socket/initSocket');
const initRouter = require('./router/index.js');
const bodyParser = require('body-parser');
const handleAuth = require('./middleware/handleAuth');
const handleError = require('./middleware/handleError');
const handleParams = require('./middleware/handleParams');
const { saveKeyPair } = require("./utils/crypto.js")
require('express-async-errors');
// 配置解析 application/x-www-form-urlencoded 格式数据的内置中间件
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.text());
app.use(bodyParser.json());
// 设置跨域和相应数据格式 
app.all('*', function (req, res, next) {
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
    res.setHeader("Access-Control-Expose-Headers", "Authorization")
    if (req.method == 'OPTIONS') {
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
        res.setHeader("Access-Control-Max-Age", "3600")
        res.setHeader("Vary", "Origin")
        res.setHeader("Access-Control-Allow-Origin", "http://localhost:5174")
        /*让options请求快速返回*/
        res.sendStatus(200)
    } else {
        next()
    }
})

app.use(handleParams);
app.use(handleAuth);
socket.initSocket(httpServer);
initRouter(app)

app.use(handleError);


httpServer.listen(3000, () => {
    //saveKeyPair()
    console.log("server is running on port 3000")
}) 